package com.luming.service;

import com.luming.dao.FinancialDataMapper;
import com.luming.entity.FinancialData;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

@Service
@RequiredArgsConstructor
public class FinancialDataServiceImpl implements FinancialDataService {
    
    private final FinancialDataMapper financialDataMapper;
    
    @Override
    public void saveData(FinancialData data) {
        financialDataMapper.insert(data);
    }
    
    @Override
    public List<FinancialData> getByFiscalYear(Integer year) {
        return financialDataMapper.findByFiscalYear(year);
    }
    
    @Override
    public List<FinancialData> getByDataName(String name) {
        return financialDataMapper.findByDataName(name);
    }
    
    @Override
    @Transactional
    public void testBatchInsert() {
        // 批量插入不同年度的数据
        for (int i = 1; i <= 10; i++) {
            FinancialData data = new FinancialData();
            data.setFiscalYear(2023 + (i % 3)); // 2023, 2024, 2025 循环
            data.setDataName("TestData-" + i);
            data.setAmount(BigDecimal.valueOf(ThreadLocalRandom.current().nextDouble(1000, 10000)));
            
            financialDataMapper.insert(data);
            System.out.println("Inserted data for year: " + data.getFiscalYear() + ", ID: " + data.getId());
        }
    }
    
    @Override
    @Transactional
    public void testCrossYearTransaction() {


        // 测试跨年度的分布式事务
        FinancialData data2023 = new FinancialData();
        data2023.setFiscalYear(2023);
        data2023.setDataName("Cross-Year-Transaction");
        data2023.setAmount(BigDecimal.valueOf(5000));
        financialDataMapper.insert(data2023);
        
        FinancialData data2024 = new FinancialData();
        data2024.setFiscalYear(2024);
        data2024.setDataName("Cross-Year-Transaction");
        data2024.setAmount(BigDecimal.valueOf(8000));
        financialDataMapper.insert(data2024);
        
        // 模拟异常，测试事务回滚
        if (true) {
            throw new RuntimeException("Test transaction rollback");
        }
        
        FinancialData data2025 = new FinancialData();
        data2025.setFiscalYear(2025);
        data2025.setDataName("Cross-Year-Transaction");
        data2025.setAmount(BigDecimal.valueOf(10000));
        financialDataMapper.insert(data2025);
    }
}